<?php
declare(strict_types=1);

namespace App\Libs;



use Hyperf\Context\ApplicationContext;
use Psr\SimpleCache\CacheInterface;
use League\Flysystem\Filesystem;
use Hyperf\Di\Annotation\Inject;
use Intervention\Image\ImageManager;
use Intervention\Image\Drivers\Imagick\Driver;
use Hyperf\Collection\Arr;
use App\Model\UserLibrary;
class BuildLibrary
{
    /**
     * @var Filesystem
     */
    #[Inject]
    private Filesystem $filesystem;

    private ImageManager $manager;

    

    public function __construct(\Hyperf\Filesystem\FilesystemFactory $factory){
        // $this->oss = $factory->get('local');
        $this->manager = new ImageManager(new Driver());

    }

    public function start($data)
    {
        $image = $this->manager->create(500, 500);
        $image->setResolution(300, 300);

        $image->save('/data/wwwroot/api.pod.finaly.cn/public/2.png');

        $image = $this->manager->read('/data/wwwroot/api.pod.finaly.cn/public/2.png');
        var_dump($image->resolution());
        // $this->filesystem->write('uploads/users/4/20250918/1-1.png', (String)$image->getImageBlob());
        $this->filesystem->write('uploads/users/4/20250918/1-1.png', file_get_contents('/data/wwwroot/api.pod.finaly.cn/public/1.png'));
        return false;

        $width = $this->cmToPx($data['product']['width']);
        $height = $this->cmToPx($data['product']['height']);
        $produce_image = [];
        foreach ($data['attr'] as $k=>$attr) {
            $image = $this->manager->create($width, $height);
            $image->setResolution($data['dpi'], $data['dpi']);
            // $this->filesystem->write('uploads/users/4/20250918/1-1.png', (String)$image->toPng());
            // return false;
            foreach ($attr['json']['bottom']['children'] as $key=>$value) {
                $size = $this->convertCoordinates(Arr::only($value['attrs'], ['x', 'y', 'width', 'height']), $attr['json']['bottom']['attrs']['width'], $attr['json']['bottom']['attrs']['height'], $width, $height );
                $imageArr = Arr::first($attr['json']['imageJson'], function($item) use ($value){
                    return $item['id'] == $value['attrs']['id'];
                });
                if(!$imageArr)continue;
                $body = $this->manager->read($this->filesystem->read($this->extractPathFromUrl($imageArr['url'])))->resize($size['width'], $size['height']);
                $body->setResolution(300, 300);
                var_dump($body->resolution());
                // return false;
                $image->place($body, 'top-left', $size['x'], $size['y']);
            }
            $image->setResolution(300, 300);
            $encoded = (String)$image->toPng();
            $url = 'uploads/users/' . $data['user_id'] . date('/Ymd') .'/' . $data['id'] . '-' . $k . '.png';
            $this->filesystem->write($url, $encoded);
            $produce_image[] = $url;
        }
        UserLibrary::where('id', $data['id'])->update(['produce_image'=> json_encode($produce_image)]);

        return 1;
    }
    /**
     * 坐标尺寸转换函数
     * 根据原始参考尺寸和当前实际尺寸，计算对应的坐标和尺寸
     * 
     * @param array $originalCoords 原始坐标和尺寸数组 [x, y, width, height]
     * @param float $refWidth 原始参考宽度
     * @param float $refHeight 原始参考高度
     * @param float $currentWidth 当前实际宽度
     * @param float $currentHeight 当前实际高度
     * @return array 转换后的坐标和尺寸数组 [x, y, width, height]
     */
    function convertCoordinates($originalCoords, $refWidth, $refHeight, $currentWidth, $currentHeight) {
        // 验证输入参数
        if ($refWidth <= 0 || $refHeight <= 0 || $currentWidth <= 0 || $currentHeight <= 0) {
            throw new InvalidArgumentException("宽度和高度必须大于0");
        }
        
        if (count($originalCoords) !== 4) {
            throw new InvalidArgumentException("原始坐标数组必须包含4个值: x, y, width, height");
        }
        $width = $originalCoords['width'];
        $height = $originalCoords['height'];
        $x = $originalCoords['x'];
        $y = $originalCoords['y'];
        // 计算宽高比例
        $widthRatio = $currentWidth / $refWidth;
        $heightRatio = $currentHeight / $refHeight;
        
        // 按比例转换坐标和尺寸
        $newX = $x * $widthRatio;
        $newY = $y * $heightRatio;
        $newWidth = $width * $widthRatio;
        $newHeight = $height * $heightRatio;
        
        return [
            'x' => intval($newX),
            'y' => intval($newY),
            'width' => intval($newWidth),
            'height' => intval($newHeight)
        ];
    }


    /**
     * 从URL中提取路径部分
     * @param string $url 完整URL
     * @return string 文件路径
     */
    public function extractPathFromUrl(string $url): string
    {
        $parsed = parse_url($url);
        return $parsed['path'] ?? '';
    }

    /**
     * 将厘米转换为像素（基于300dpi分辨率）
     * @param float $cm 厘米值
     * @return int 像素值
     */
    public function cmToPx(float $cm): int
    {
        return (int) round($cm * 300 / 2.54);
    }


    public static function getInstance()
    {
        return ApplicationContext::getContainer()->get(CacheInterface::class);
    }

    public static function __callStatic($name, $arguments)
    {
    	return self::getInstance()->$name(...$arguments);
    }
}